function writeClipboard(text) {
	chrome.extension.sendRequest({
		action: 'writeClipboard',
		args: [text],
		errback: function(){
			alert('Copy Error');
		},
	}, function(){
		//console.log('Copy OK');
	});
}

function getOption(optionName, callback) {
	chrome.extension.sendRequest({
		action: 'getOption',
		args: (optionName instanceof Array ? optionName : [optionName]),
	}, callback);
}

var SYSTEM_MESSAGE_IMAGE = 'icon_message_system.png';
var DELETED_MESSAGE_IMAGE = 'icon_message_delete.png';

var MENU_ITEMS = [
//	['Delete', menuItem_delete_click],
	['Copy Message', menuItem_copymessage_click],
	['Copy Message URL', menuItem_copymessageurl_click],
	['Copy URLs in Message', menuItem_copyurls_click],
];
//console.info("document end");

if (window && window.jQuery) {
	//console.debug('jquery is enabled', window.jQuery);
	getOption(['HideDeletedMessage', 'EnableShiftEnter', 'EnableCtrlEnter'], function(options){
		//console.log('options', options);
		onDocumentEnd(options);
	});
} else {
	console.debug('jquery is disabled');
}

function onDocumentEnd(options) {
	$('div#mbox_cont > div.mbox_list > ul.rrlist > li[id^="MESSAGE_"]').each(function(idx, msgItem){
		decorateMessageItem(msgItem, options.HideDeletedMessage);
	});
	$('div#mbox_cont > div.mbox_list > ul.rrlist').on('DOMNodeInserted', function(event){
		var mutationEvent = event.originalEvent;
		//console.log('fired DOMNodeInserted', mutationEvent);
		if (mutationEvent.target instanceof HTMLLIElement
		  && mutationEvent.target.id
		  && mutationEvent.target.id.indexOf('MESSAGE_') === 0) {
			decorateMessageItem(mutationEvent.target, options.HideDeletedMessage);
		
		} else if (mutationEvent.target instanceof Text
		  && mutationEvent.target.textContent === 'Deleted message'
		  && mutationEvent.target.parentElement.className === 'msg_cont'
		  && mutationEvent.target.parentElement.parentElement.className === 'msglist'
		  && mutationEvent.target.parentElement.parentElement.parentElement.id
		  && mutationEvent.target.parentElement.parentElement.parentElement.id.indexOf('MESSAGE_') === 0) {
			var msgItem = $(mutationEvent.target.parentElement.parentElement.parentElement);
			
			// remove rrext menu
			var msgIdElem = msgItem.find('.message_id');
			if (msgIdElem) {
				var msgId = msgIdElem.text();
				var menuId = 'rrext-container-menu-'+msgId;
				$('#'+menuId).remove();
			}

			if (options.HideDeletedMessage) {
				hideMessageItem(msgItem, true);
			}
		}
	});
	$('div#mbox_cont div.msg_f01 textarea').on('keypress', function(event){
		var keyEvent = event.originalEvent;
		if (// Shift + Enter
			keyEvent.shiftKey == true && keyEvent.keyCode === 13 && options.EnableShiftEnter
			// Ctrl + Enter(Win)
			|| keyEvent.ctrlKey == true && keyEvent.keyCode === 10 && options.EnableCtrlEnter
			// Ctrl + Enter(Mac)
			|| keyEvent.ctrlKey == true && keyEvent.keyCode === 13 && options.EnableCtrlEnter
			) {
			event.preventDefault();
			$('#bt_msg_01_send').click();
		}
	});
};

function hideMessageItem(msgItem, isAnimate) {
	var _setclass = function() {
		msgItem.addClass('rrext-deleted-message');
	};
	if (isAnimate) {
		msgItem.hide(function(){
			_setclass();
		});
	} else {
		_setclass();
	}
}


function decorateMessageItem(msgItem, isHideDeletedMessage) {
	msgItem = $(msgItem);

	var imgName = msgItem.find('img.user_thumb').attr('src');
	if (imgName && imgName.indexOf(DELETED_MESSAGE_IMAGE) >= 0) {
		// Deleted Message
		if(isHideDeletedMessage) hideMessageItem(msgItem);
		return;
	} else if (imgName && imgName.indexOf(SYSTEM_MESSAGE_IMAGE) >= 0) {
		// System Message
		return;
	}

	var msgId = msgItem.find('.message_id').text();
	var menuId = 'rrext-container-menu-'+msgId;
	msgItem
	// class="rrext-container-menu"
	.after($('<div class="rrext-container-menu">')
		.attr('id', menuId)
		// class="rrext-menu"
		.append($('<div>')
			.addClass('rrext-menu')
			// class="rrext-menu-pane"
			.append($('<div>')
				.addClass('rrext-menu-pane'))
			// class="rrext-menu-item"
			.each(function(){
				for (var i in MENU_ITEMS) {
					$(this).append($('<a>')
						.addClass('rrext-menu-item')
						.text(MENU_ITEMS[i][0])
						.attr('href', 'javascript:void(0);')
						.attr('title', MENU_ITEMS[i][0])
						.on('click', (function(menuItemFunc) {
							return function() { menuItemFunc(msgId); };
						})(MENU_ITEMS[i][1]))
					)
				}
			})
		)
	);
}

function removeMenuContainer(msgId) {
	$('#rrext-container-menu-'+msgId).remove();
}

function menuItem_delete_click(msgId) {

	if (confirm('Delete this message.')) {
		var msgItem = $("#MESSAGE_" + msgId);
		
		var dummyElement = null;
		
		if ($('#my_frame')) $('#my_frame').remove();

		$(document.body).append($('<iframe class="rrext-dummy-frame" id="my_frame">'));
		var dummyFrame = $('#my_frame');
		var dummyFrameDoc = dummyFrame.contents();
		dummyFrameDoc[0].open();
		dummyFrameDoc[0].close();
		dummyFrameDoc.find('body')
			.append($('<div class="msg_uid">')
				.text(msgId)
			);

		
		var _deleteCallback = function(event) {
			var mutationEvent = event.originalEvent;
			//console.log('DELETE MUTATION:', mutationEvent);
			if (mutationEvent.target instanceof HTMLBRElement) {
				//console.log('call _deleteCallback');
				dummyFrame.remove();
				msgItem.find('.msg_cont').off('DOMNodeInserted', _deleteCallback);
				removeMenuContainer(msgId);
				hideMessageItem(msgItem, true);
			}
		};

		msgItem.find('.msg_cont').on('DOMNodeInserted', _deleteCallback);

		$('#bt_delete_message').click();
	}
}
function menuItem_copymessage_click(msgId) {
	$("#MESSAGE_" + msgId).each(function(idx, msgItem){
		msgItem = $(msgItem);
		var msgTime    = msgItem.find('.msg_time')
			.contents()
			.filter(function(i, elem){
				return elem instanceof Text})
			.text();
		var msgUser    = msgItem.find('.user_name').text();
		var msgContent = '';
		var msgImageUrl = '';
		msgItem.find('.msg_cont').contents()
			.each(function(i, elem){
				if (elem instanceof HTMLBRElement) {
					msgContent += '\n';
				} else if (elem instanceof HTMLImageElement) {
					msgImageUrl += elem.src.replace(/m\.jpg$/, 'l.jpg');
				} else {
					msgContent += $(elem).text();
				}
			});
		if (msgContent.length > 4) {
			if (msgContent.substring(msgContent.length - 4) === '<br>') {
				msgContent = msgContent.substring(0, msgContent.length - 4);
			}
		}
		
		getOption(msgImageUrl ? 'MessageTemplateWithImage' : 'MessageTemplateDefault', function(template){
			writeClipboard(template
					.replace(/<user>/g, msgUser)
					.replace(/<time>/g, msgTime)
					.replace(/<content>/g, msgContent)
					.replace(/<image_url>/g, msgImageUrl));
		});

	});/* end of each*/
}

function menuItem_copymessageurl_click(msgId) {
	if ($('#'+msgId).length) {
		var url = location.origin + $('#'+msgId).attr('href');
		url = url.substring(url, url.length-'?overlay=true'.length);
		writeClipboard(url);
	} else {
		console.error('Copy failed. '+ msgId +'is not exist.');
	}
}
function menuItem_copyurls_click(msgId) {
	$("#MESSAGE_" + msgId).each(function(idx, msgItem){
		msgItem = $(msgItem);
		var urls = '';
		msgItem.find('.msg_cont').contents()
			.each(function(i, elem){
				if (elem instanceof HTMLAnchorElement) {
					urls += elem.href + '\n';
				}
			});
		if (urls) writeClipboard(urls);
	});/* end of each*/
}
